/*
 * Famon (http://code.google.com/p/famon/)
 * Copyright (c) 2010 Carl Crous.
 *
 * This file is part of Famon.
 *
 * Famon is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Famon is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Famon.  If not, see <http://www.gnu.org/licenses/>.
 */

package za.org.foobar.famon.frontend.server;

import com.google.appengine.api.datastore.Key;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.gwtportlets.portlet.smartgwt.client.CriteriaDto;
import za.org.foobar.famon.frontend.client.dto.FailureDto;
import za.org.foobar.famon.frontend.client.dto.LoggingEventDto;
import za.org.foobar.famon.frontend.client.dto.StackTraceElementDto;
import za.org.foobar.famon.frontend.client.dto.ThreadDto;
import za.org.foobar.famon.frontend.server.util.ServerUtil;
import za.org.foobar.famon.model.StackTraceElement;
import za.org.foobar.famon.util.DB;
import za.org.foobar.famon.util.DBQuery;

import java.util.ArrayList;
import java.util.List;


/**
 *
 */
public class FailureLogic {
    private final Log log = LogFactory.getLog(getClass());
    private final ApplicationLogic applicationLogic = ApplicationLogic.get(); 

    private static FailureLogic instance;
    public static FailureLogic get() {
        return instance == null ? instance = new FailureLogic() : instance;
    }

    public FailureLogic() {
        log.debug("Creating FailureLogic");
    }

    public List<FailureDto> getFailureDtoList() {
        return createFailureDtoList(getFailureList());
    }

    public List<Failure> getFailureList() {
        return getFailureList("date desc");
    }

    public List<Failure> getFailureList(String orderBy) {
        return DB.createDBQuery(Failure.class)
            .addOrderBy(orderBy).getResultList();
    }

    public List<FailureDto> getFailureDtoList(Key applicationGroupId) {
        return getFailureDtoList(applicationGroupId, null);
    }

    public List<FailureDto> getFailureDtoList(Key applicationGroupId, String orderBy) {
        List<Failure> resultList = getFailureList(applicationGroupId, orderBy);
        return createFailureDtoList(resultList);
    }

    public List<Failure> getFailureList(Key applicationGroupId) {
        return getFailureList(applicationGroupId, null);
    }

    public List<Failure> getFailureList(Key applicationGroupId, String orderBy) {
        // Check security
        DBQuery<Failure> q = getFailureQuery(applicationGroupId, orderBy);
        return q.getResultList();
    }

    public DBQuery<Failure> getFailureQuery(Key applicationGroupId, String orderBy) {
        applicationLogic.getApplicationGroup(applicationGroupId);
        if (orderBy == null || orderBy.length() == 0) {
            orderBy = "date desc";
        }
        DBQuery<Failure> q = DB.createDBQuery(Failure.class)
                .addWhere("applicationGroupId", applicationGroupId)
                .addOrderBy(orderBy);
        return q;
    }

    public List<ThreadDto> getThreadDtoList(Failure failure) {
        return createThreadDtoList(failure.getThreadList());
    }

    public List<StackTraceElementDto> getStackTraceElementDtoList(ThreadInformation thread) {
        return createStackTraceElementDtoList(thread.getStackTrace());
    }

    public List<LoggingEventDto> getLoggingEventDtoList(ThreadInformation thread) {
        return createLoggingEventDtoList(thread.getLoggingEventList());
    }

    public Failure getFailure(Key failureId) {
        Failure failure = DB.createDBQuery(Failure.class)
                .addWhere("id", failureId)
                .getSingleResult();
        if (failure != null) {
            applicationLogic.checkViewApplication(failure.getApplicationGroup().getApplication());
        }
        return failure;
    }

    public FailureDto getFailureDto(Key failureId) {
        return createFailureDto(getFailure(failureId));
    }

    public Failure getFailure(CriteriaDto c, String idField) {
        return FailureLogic.get().getFailure(ServerUtil.getKeyFromCriteria(c, Failure.class, idField));
    }

    public ThreadInformation getThreadInformation(Key threadInformationId) {
        return DB.createDBQuery(ThreadInformation.class)
            .addWhere("id", threadInformationId)
            .getSingleResult();
    }

    public ThreadInformation getThreadInformation(CriteriaDto c, String failureIdField, String threadIdField) {
        Key failureId = ServerUtil.getKeyFromCriteria(c, Failure.class, failureIdField);
        Key threadId = ServerUtil.getKeyFromCriteria(c, failureId, ThreadInformation.class, threadIdField);
        return FailureLogic.get().getThreadInformation(threadId);
    }

    public List<FailureDto> createFailureDtoList(List<Failure> failures) {
        List<FailureDto> dtos = new ArrayList<FailureDto>();
        for (Failure failure : failures) {
            dtos.add(createFailureDto(failure));
        }
        return dtos;
    }

    public FailureDto createFailureDto(Failure failure) {
        if (failure == null) {
            return null;
        }
        FailureDto dto = new FailureDto();
        dto.id = Long.toString(failure.getId().getId());
        dto.applicationGroupId = Long.toString(failure.getApplicationGroupId().getId());
        dto.user = failure.getUser();
        dto.failureType = failure.getFailureType();
        dto.message = failure.getMessage();
        dto.date = failure.getDate();

        dto.sourceHostname = failure.getSourceHostname();
        dto.sourceAddress = failure.getSourceAddress();
        dto.sourcePort = failure.getSourcePort();
        dto.originalSourceAddress = failure.getOriginalSourceAddress();
        dto.originalSourceHostname = failure.getOriginalSourceHostname();
        return dto;
    }

    public List<ThreadDto> createThreadDtoList(List<ThreadInformation> threadList) {
        List<ThreadDto> threadDtoList = new ArrayList<ThreadDto>(threadList.size());
        for (ThreadInformation t : threadList) {
            threadDtoList.add(createThreadDto(t));
        }
        return threadDtoList;
    }

    public ThreadDto createThreadDto(ThreadInformation thread) {
        ThreadDto dto = new ThreadDto();
        dto.id = Long.toString(thread.getId().getId());
        dto.failureId = Long.toString(thread.getFailure().getId().getId());
        dto.name = thread.getName();
        return dto;
    }

    public List<StackTraceElementDto> createStackTraceElementDtoList(List<StackTraceElement> stackTrace) {
        List<StackTraceElementDto> stackTraceDto = new ArrayList<StackTraceElementDto>(stackTrace.size());
        for (StackTraceElement stackTraceElement : stackTrace) {
            stackTraceDto.add(createStackTraceElementDto(stackTraceElement));
        }
        return stackTraceDto;
    }

    public List<LoggingEventDto> createLoggingEventDtoList(List<LoggingEvent> loggingEventList) {
        List<LoggingEventDto> loggingEventDtoList = new ArrayList<LoggingEventDto>();
        for (LoggingEvent loggingEvent : loggingEventList) {
            loggingEventDtoList.add(createLoggingEventDto(loggingEvent));
        }
        return loggingEventDtoList;
    }

    public StackTraceElementDto createStackTraceElementDto(StackTraceElement stackTraceElement) {
        StackTraceElementDto dto = new StackTraceElementDto();
        dto.id = Long.toString(stackTraceElement.getId().getId());
        dto.threadId = Long.toString(stackTraceElement.getThread().getId().getId());
        dto.index = stackTraceElement.getIndex();
        SourceLocation sourceLocation = stackTraceElement.getSourceLocation();
        dto.fileName = sourceLocation.getFileName();
        dto.lineNumber = sourceLocation.getLineNumber();
        dto.className = sourceLocation.getClassName();
        dto.methodName = sourceLocation.getMethodName();
        return dto;
    }

    public LoggingEventDto createLoggingEventDto(LoggingEvent loggingEvent) {
        LoggingEventDto dto = new LoggingEventDto();
        dto.id = Long.toString(loggingEvent.getId().getId());
        dto.threadId = Long.toString(loggingEvent.getThread().getId().getId());
        dto.index = loggingEvent.getIndex();
        dto.loggerName = loggingEvent.getLoggerName();
        dto.level = loggingEvent.getLevel();
        dto.message = loggingEvent.getMessage();
        SourceLocation sourceLocation = loggingEvent.getSourceLocation();
        dto.fileName = sourceLocation.getFileName();
        dto.lineNumber = sourceLocation.getLineNumber();
        dto.className = sourceLocation.getClassName();
        dto.methodName = sourceLocation.getMethodName();
        return dto;
    }
}
